package com.example.music;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.music.DB.CollectInfo;
import com.example.music.DB.LoveInfo;
import com.example.music.DB.SongInfo;
import com.example.music.DB.UserInfo;
import com.example.music.Utils.FullScreenDialogFragment;
import com.example.music.Utils.MusicPlayer;
import com.example.music.Utils.MusicPlaylist;
import com.example.music.Utils.PlayListDialogFragment;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    ImageView playBtn, preSong, laterSong;
    SeekBar positionBar;
    TextView elapsedTimeLabel;
    TextView remainingTimeLabel;
    TextView songTitle;
    TextView songAuthor;
    ImageView ifLike, toShare, toDownload;
    ImageView backSpace, songSeal;
    ImageView play_list,recyle_btn;     //播放列表和循环控制
    MusicPlayer musicPlayer;
    int totalTime;
    MusicPlaylist mData;
    private SharedPreferences sharedPreferences;

    //初始化
    public void init() {

        /***********获取音乐单例***************/
        musicPlayer = MusicPlayer.getInstance();
        mData = MusicPlaylist.getInstance();
        sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);

        //播放按钮 + 开始/结束时间
        playBtn = (ImageView) findViewById(R.id.playbtn);
        if (musicPlayer.isPlaying())
            playBtn.setBackgroundResource(R.drawable.play_button);
        else
            playBtn.setBackgroundResource(R.drawable.icon_play);
        preSong = (ImageView) findViewById(R.id.preSong);
        laterSong = (ImageView) findViewById(R.id.laterSong);

        elapsedTimeLabel = (TextView) findViewById(R.id.start_time);
        remainingTimeLabel = (TextView) findViewById(R.id.end_time);

        //歌曲名、作者
        songTitle = findViewById(R.id.music_title);
        songAuthor = findViewById(R.id.music_author);

        //喜欢、分享、下载
        ifLike = (ImageView) findViewById(R.id.if_like);
        toShare = (ImageView) findViewById(R.id.toshare);
        toDownload = (ImageView) findViewById(R.id.todownload);
        songSeal = (ImageView) findViewById(R.id.seal_image);

        positionBar = (SeekBar) findViewById(R.id.positionBar); //进度条
        backSpace = (ImageView) findViewById(R.id.backbtn);     //返回

        //播放列表和循环控制
        play_list = findViewById(R.id.play_list);
        recyle_btn = findViewById(R.id.recyle_btn);
    }

    public void LoveIconListener(){
        if(mData.getCurrentSongIndex()!=-1) {
            int curUserId = sharedPreferences.getInt("curUserId", -1);
            if (curUserId != -1) {
                List<LoveInfo> LoveSongList = LitePal
                        .select("UserId,SongId")
                        .where("UserId = ? and SongId = ?", String.valueOf(curUserId), String.valueOf(mData.getCurrentSongIndex() + 1))
                        .find(LoveInfo.class);

                if (!LoveSongList.isEmpty()) {
                    ifLike.setBackgroundResource(R.drawable.icon_love_focus);
                }else
                    ifLike.setBackgroundResource(R.drawable.icon_love);

            }
        }
    }

    public void initListener() {
        //喜欢、分享、下载、播放、返回
        ifLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int curUserId = sharedPreferences.getInt("curUserId",-1);
                if(curUserId < 0) {
                    showToast("用户未登录，请先登录！");
                    return;
                }
                if(mData.getCurrentSongIndex()<0) {
                    showToast("暂无歌曲播放！");
                    return;
                }
                //如果当前用户喜欢了此歌曲
                List<LoveInfo> LoveSongList = LitePal
                        .select("UserId,SongId")
                        .where("UserId = ? and SongId = ?",String.valueOf(curUserId),String.valueOf(mData.getCurrentSongIndex()+1))
                        .find(LoveInfo.class);

                if(LoveSongList.isEmpty()) {  //新加记录
                    LoveInfo loveAdd = new LoveInfo(curUserId, mData.getCurrentSongIndex()+1);
                    loveAdd.save();
                    ifLike.setBackgroundResource(R.drawable.icon_love_focus);
                    showToast("添加喜欢成功！");
                }else {
                    ifLike.setBackgroundResource(R.drawable.icon_love);
                    LoveInfo loveDelete = new LoveInfo(curUserId,mData.getCurrentSongIndex()+1);
                    LitePal.deleteAll(LoveInfo.class, "UserId = ? and SongId = ?", String.valueOf(curUserId), String.valueOf(mData.getCurrentSongIndex()+1));
                    showToast("取消喜欢成功！");
                }
            }
        });
        toShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showToast("此功能暂未上线！");
            }
        });
        toDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showToast("此功能暂未上线！");
            }
        });
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!musicPlayer.isPlaying()) {
                    musicPlayer.resume();
                    playBtn.setBackgroundResource(R.drawable.play_button);
                } else {
                    musicPlayer.pause();
                    playBtn.setBackgroundResource(R.drawable.icon_play);
                }
            }
        });
        preSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int curSongIndex = mData.getCurrentSongIndex();
                if (curSongIndex > 0) {
                    playBtn.setBackgroundResource(R.drawable.play_button);
                    Message msg = new Message();
                    msg.what = musicPlayer.getCurrentPosition();
                    handler.sendMessage(msg);

                    musicPlayer.stop();
                    musicPlayer.play(mData.getSongs().get(curSongIndex - 1));
                    mData.setCurrentSongIndex(curSongIndex - 1);
                    return;
                }
                showToast("已经是第一曲了！");
            }
        });
        laterSong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int curSongIndex = mData.getCurrentSongIndex();
                if (curSongIndex < mData.getSongs().size() - 1) {
                    playBtn.setBackgroundResource(R.drawable.play_button);
                    Message msg = new Message();
                    msg.what = musicPlayer.getCurrentPosition();
                    handler.sendMessage(msg);

                    musicPlayer.stop();
                    musicPlayer.play(mData.getSongs().get(curSongIndex + 1));
                    Log.d("播放记录：",musicPlayer.getPlaybackHistory().toString());
                    mData.setCurrentSongIndex(curSongIndex + 1);
                    return;
                }
                showToast("已经是最后一曲了！");
            }
        });
        backSpace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        songSeal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jumpTo(songDetailActivity.class);
            }
        });
        positionBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    musicPlayer.seekTo(progress);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        //playlist && recyle_btn
        play_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlayListDialogFragment dialogFragment = new PlayListDialogFragment();
                dialogFragment.show(getSupportFragmentManager(), "PlayLiistFragment");
            }
        });
        recyle_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("功能暂未上线！");
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initListener();

        //开启一个线程更新UI
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if(musicPlayer.isPlaying()) {
                        try {
                            Message msg = new Message();
                            msg.what = musicPlayer.getCurrentPosition();
                            handler.sendMessage(msg);
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            }
        }).start();
    }

    //实时更新UI
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int currentPosition = msg.what;
            totalTime = musicPlayer.getDuration();     //得到持续时间
            positionBar.setMax(totalTime);             //设置label

            //进度条更新
            positionBar.setProgress(currentPosition);

            //更新时间标签
            String elapsedTime = createTimeLabel(currentPosition);
            elapsedTimeLabel.setText(elapsedTime);
            String remainTime = createTimeLabel(totalTime - currentPosition);
            remainingTimeLabel.setText("- " + remainTime);

            //歌名作者更新
            int index = mData.getCurrentSongIndex();
            songTitle.setText(mData.getSongs().get(index).getSong());
            songAuthor.setText(mData.getSongs().get(index).getSinger());

            //图标更新
            LoveIconListener();
        }
    };

    //工具
    public String createTimeLabel(int time) {
        String timeLabel = "";
        int min = time / 1000 / 60;
        int sec = time / 1000 % 60;

        timeLabel = min + ":";
        if (sec < 10) timeLabel += "0";
        timeLabel += sec;

        return timeLabel;
    }
    public void jumpTo(Class context) {
        Intent intent = new Intent(MainActivity.this, context);
        startActivity(intent);
    }
    public void showToast(String msg) {
        // 创建一个Toast消息
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
